package com.widget;

import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Handler;
import android.util.Log;

public class ListParser implements ParseStreaming {
	private int count;
	private int track = 0;
	
	private Handler mContext;
	private String root_string="";
	private boolean flag = false;
	private String totalContent="";
	
	ArrayList <String> dataFiles = new ArrayList <String>();
	
	public int fuzzyParse(String content){
		
		String [] lsOutput = content.split("\r\n");
		Pattern root = Pattern.compile("[0-9a-zA-Z.//_-]+:$");
		//Pattern child = Pattern.compile("([0-9a-zA-Z.//_-]+)$");
		Pattern end = Pattern.compile("#");
		for(int i=1;i<lsOutput.length;i++)
		{
			Matcher r = root.matcher(lsOutput[i]);
			//Matcher c = child.matcher(lsOutput[i]);
			Matcher e = end.matcher(lsOutput[i]);
			String child_string="";
			if(r.find()){
				root_string = r.group(0);
				root_string = root_string.substring(0,root_string.length()-1);
				Log.d("ROOT_STRING",root_string);
				flag = true;
				dataFiles.add(root_string);
				}
			else if(lsOutput[i].length()>0){
				//child_string = c.group(0);
				child_string = lsOutput[i];
				child_string = root_string+"/"+child_string;
				Log.d("CHILD_STRING",child_string);
				if(!child_string.contains("#"))
					dataFiles.add(child_string);
			}
			
			if(e.find() && flag) {
				
				return 0;
			}
		
		}
		return 1;
	}
	@Override
	public int parseString(String content) {
		totalContent += content; 
		Log.d("IMPORTANT",content);
		if(fuzzyParse(totalContent)==0){
			flag = false;
			dataFiles = new ArrayList<String>();
			fuzzyParse(totalContent);
			Log.d("FuzzyParse", "Fuzzy Parse Donw Yupy!!!"+dataFiles.size());
			mContext.sendEmptyMessage(ACQUIRED);
			return 0;
		}
		
		
		return 1;
	}
	public ArrayList <String> getDataFiles(){
		return dataFiles;
	}
	
	@Override
	public void endMatcher(int n, Handler c) {
		count=n;
		mContext =  c;


	}

}
